<template>
    <div>
        <el-button type="primary"style="margin-left: 3px" @click="addNewReg()">
            <el-icon>
                <Edit/>
            </el-icon> &nbsp;挂号
        </el-button>

        <el-button type="primary"style="margin-left: 3px" @click="clear()">
            <el-icon>
                <Refresh/>
            </el-icon>&nbsp;清空
        </el-button>

        <br><br>
        <el-row :gutter="2">
            <el-col :span="5">
                <div>
                    <span style="color:red; visibility: hidden">*</span> 
                    <span style="font-size:13px;font-family:'Microsoft YaHei'">挂号信息</span>&nbsp;
                    <el-input 
                        placeholder="系统自动生成" 
                        style="width: 200px" 
                        v-model="formData.casenumber"
                        :disabled="true"
                    >
                        <template #append>
                            <el-button @click="generateCaseNumber">
                                <el-icon><Refresh /></el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </div>
            </el-col>

            
            <el-col :span="5">
                <div class="grid-content bg-purple">
                    <span style="color:red">*</span>
                    
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:</span>&nbsp;
                    <el-input placeholder="输入姓名" style="width: 200px" again="left" 
                              v-model="formData.realname">
                    </el-input>
                </div>
            </el-col>

            <el-col :span="5">
                <div class="grid-content bg-purple">
                    <span style="color:red">*</span>
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</span>&nbsp;
                    <el-select placeholder="选择性别" style="width: 100px"  v-model="formData.gender">
                        <el-option
                                v-for="item in sexData"
                                :key="item.id"
                                :label="item.constantname"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </div>
            </el-col>

            <el-col :span="7">
                <div class="grid-content bg-purple">
                    <span style="color:red">*</span>
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">年&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;龄:</span>&nbsp;
                    <el-input placeholder="输入年龄" style="width: 200px" again="left"  v-model="formData.age">
                    </el-input>
                    <span style="color:red">*</span>
                    <el-select placeholder="选择岁" style="width: 150px"  v-model="formData.agetype">
                        <el-option label="岁" value="岁"></el-option>
                        <el-option label="月" value="月"></el-option>
                        <el-option label="天" value="天"></el-option>
                    </el-select>
                </div>
            </el-col>

        </el-row>

        <el-row :gutter="2">
    
            <el-col :span="5">
                <div class="grid-content bg-purple">
                    <span style="color:red; visibility: hidden">*</span> 
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">出生日期:</span>&nbsp;
                    <el-date-picker
                            @change="calculateAge"
                            v-model="formData.birthdate"
                            type="date"
                            placeholder="出生日期"  style="width: 150px" value-format="YYYY-MM-DD">
                    </el-date-picker>

                </div>
            </el-col>
            <el-col :span="10">
                <div class="grid-content bg-purple">
                    <span style="color:red; visibility: hidden">*</span>
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">身份证号:</span>&nbsp;
                    <el-input placeholder="在此输入身份证号" style="width: 300px"
                              v-model="formData.idnumber"></el-input>
                </div>
            </el-col>
            <el-col :span="7">
                <div class="grid-content bg-purple">
                    <span style="color:red; visibility: hidden">*</span>
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">家庭住址:</span>&nbsp;
                    <el-input placeholder="在此输入家庭住址" style="width: 350px" again="left" 
                              v-model="formData.homeaddress">
                    </el-input>
                </div>
            </el-col>
        </el-row>

        <el-row :gutter="2">
       <el-col :span="5">
                <div class="grid-content bg-purple">
                    <span style="color:red">*</span>
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">结算类别:</span>&nbsp;
                    <el-select placeholder="结算类别" style="width: 100px"  v-model="formData.categoryid">
                        <el-option
                                v-for="item in categoryData"
                                :key="item.id"
                                :label="item.settlename"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </div>
            </el-col>


            <el-col :span="5">
                <div class="grid-content bg-purple">
                    <span style="color:red">*</span>
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">看诊日期:&nbsp;
                        <el-date-picker
                                v-model="formData.visitdate"
                                type="date"
                                placeholder="看诊日期" style="width: 200px" value-format="YYYY-MM-DD"
                                @change="kzrq_select()">
                        </el-date-picker>

                    </span>
                </div>
            </el-col>

            <el-col :span="5">
                <div class="grid-content bg-purple">
                    <span style="color:red">*</span>
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">午&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</span>&nbsp;
                    <el-select 
                        placeholder="请选择午别" 
                        style="width: 100px" 
                        v-model="formData.noon"
                        :clearable="false"
                        @change="handleNoonChange"
                    >
                        <el-option
                            v-for="item in noonOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </div>
            </el-col>

            <el-col :span="4">
                <div class="grid-content bg-purple">
                    <span style="color:red">*</span>
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">挂号科室:</span>&nbsp;
                    <el-select placeholder="挂号科室" style="width: 108px"  v-model="formData.deptid"
                               @change="Dept_select()">
                        <el-option
                                v-for="item in deptData"
                                :key="item.id"
                                :label="item.deptname"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </div>
            </el-col>
        </el-row>


        <el-row :gutter="2">
            <el-col :span="5">
                <div class="grid-content bg-purple">
                    <span style="color:red">*</span>
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">号&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别:</span>&nbsp;

                    <el-select placeholder="号别" style="width: 100px"  v-model="formData.registleid"
                               @change="RegistLe_select()">
                        <el-option
                                v-for="item in registlevelData"
                                :key="item.id"
                                :label="item.registname"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </div>
            </el-col>

            <el-col :span="5">
                <div class="grid-content bg-purple">
                    <span style="color:red">*</span>
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">看诊医生:</span>&nbsp;
                    <el-select placeholder="看诊医生" style="width: 110px"  v-model="formData.userid">
                        <el-option
                                v-for="item in doctorData"
                                :key="item.id"
                                :label="item.realName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </div>
            </el-col>
        </el-row>



        <el-row :gutter="2">
            <el-col :span="5">
                <div>
                     <span style="color:red; visibility: hidden">*</span>
                    <span style="font-size:13px;font-family:'Microsoft YaHei'">病历本</span>
                        <input type="checkbox" v-model="formData.isbook" 
                            :true-value="1" 
                            :false-value="0"
                            @change="book_select()"
                            style="width: 20px; height: 20px;"
                        />
                </div>
            </el-col>

            <!-- <el-col :span="5">
                <div>
                    <span style="color:red">*</span>
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">应收金额:</span>&nbsp;
                    <el-input placeholder="应收金额" style="width: 100px" again="left"  v-model="formData.fee"
                              readonly>
                    </el-input>
                </div>
            </el-col> -->

            <el-col :span="4">
                <div>
                    <span style="color:red">*</span>
                    <span style="font-size:13px;height: 40px;font-family:'Microsoft YaHei'">收费方式:</span>&nbsp;
                    <el-select placeholder="收费方式" style="width: 100px"  v-model="formData.feetype">
                        <el-option
                                v-for="item in categories3"
                                :key="item.ID"
                                :label="item.constantname"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </div>
            </el-col>
        </el-row>
    </div>
</template>


<script setup>
    import {onMounted, ref} from 'vue'
    import service from '@/utils/request'
    import { useCounterStore } from "@/stores/counter.js";
    import { ElMessage } from 'element-plus'
    const counter = useCounterStore();
    

    // 午别选项
    const noonOptions = ref([
        { value: 'AM', label: '上午' },
        { value: 'PM', label: '下午' }
    ])

    let sexData = ref([])       //性别数据
    let deptData = ref([])
    let categoryData = ref([])
    let categories3 = ref([])
    let doctorData = ref([])
    let registlevelData = ref([])  // 号别源数据
    // 修改 formData 的初始值
    let formData = ref({
        noon: 'AM', // 默认上午
        isbook: 0,  // 默认未选中，值为0
        agetype: '岁' // 默认年龄类型
    })

    const addNewReg = async () => {
        let payload;
    try {
        // 0. 确保病历号已生成
        if (!formData.value.casenumber) {
            const generated = await generateCaseNumber();
            if (!generated) {
                throw new Error('请先生成病历号');
            }
        }

        // 1. 必填字段验证
        const requiredFields = [
            'casenumber', 'realname', 'gender', 'age', 'agetype',
            'categoryid', 'visitdate', 'noon', 'deptid',
            'registleid', 'userid', 'feetype'
        ];
        
        const missingFields = requiredFields.filter(field => !formData.value[field]);
        
        if (missingFields.length > 0) {
            ElMessage.warning(`请填写所有必填字段！缺失字段: ${missingFields.join(',')}`);
            return;
        }

        // 2. 准备提交数据（与后端严格一致）
        const payload = {
            casenumber: formData.value.casenumber,
            realname: formData.value.realname,
            gender: Number(formData.value.gender), // 确保为数字
            //age: Number(formData.value.age),       // 确保为数字
            agetype: formData.value.agetype,
            birthdate: formData.value.birthdate || null, // 允许为空
            idnumber: formData.value.idnumber || null,   // 允许为空
            homeaddress: formData.value.homeaddress || null, // 允许为空
            settleid: Number(formData.value.categoryid), // 字段名与后端对齐
            visitdate: formData.value.visitdate, // 日期格式应为 YYYY-MM-DD
            noon: formData.value.noon,
            deptid: Number(formData.value.deptid),
            userid: Number(formData.value.userid),
            registleid: Number(formData.value.registleid),
            feetype: Number(formData.value.feetype),
            //isbook: Number(formData.value.isbook), // 强制转换为数字 0/1
            visitstate: 1 ,// 默认状态
            gender: formData.value.gender ? Number(formData.value.gender) : null,
            age: formData.value.age ? Number(formData.value.age) : null,
            isbook: formData.value.isbook ? 1 : 0, // 更安全的布尔转换
        };

        console.log('最终提交数据:', JSON.stringify(payload, null, 2));

         // 3. 发送请求
         const res = await service.post("/register/add", payload);
        console.log('后端原始响应:', res);
        
        // 修改响应处理逻辑
        if (res.status === 200) {
            // 后端返回200状态码即视为成功
            ElMessage.success(`挂号成功！病历号: ${payload.casenumber}`);
            clearForm();
        } else {
            // 尝试解析错误信息
            let errorMsg = '操作失败';
            if (typeof res.data === 'string') {
                errorMsg = res.data;
            } else if (res.data?.message) {
                errorMsg = res.data.message;
            }
            throw new Error(errorMsg);
        }
    } catch (error) {
        console.error('完整错误信息:', {
            request: payload,
            response: error.response?.data || '无响应数据',
            error: error.message
        });
        
        ElMessage.error(error.message || '操作失败');
    }
    };

    // 修改 clearForm 方法
    const clearForm = () => {
    formData.value = {
        noon: 'AM', // 重置默认值
        isbook: 0,  // 重置为未选中状态
        agetype: '岁' // 设置默认年龄类型
        // 其他字段...
    };
    };
    // 生成病历号
    const generateCaseNumber = async () => {
    try {
    const res = await service.get("/register/maxid");
        
        // 更健壮的响应数据解析
    const maxId = res.data?.data?.maxId || 
                    res.data?.maxId || 
                    res.result?.maxId || 
                    0; // 默认从0开始
        
    const newCaseNumber = formatCaseNumber(maxId + 1);
        formData.value.casenumber = newCaseNumber;
        ElMessage.success(`病历号已生成: ${newCaseNumber}`);
        return newCaseNumber; // 返回生成的病历号
    } catch (error) {
        console.error('生成病历号错误:', error);
        ElMessage.error('病历号生成失败，请手动输入');
        return null;
    }
    };

    const formatCaseNumber = (id) => {
    const date = new Date();
    const year = date.getFullYear().toString().slice(-2);
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    return `${year}${month}${id.toString().padStart(4, '0')}`;
    };

    
    const kzrq_select = () => {
    // 1. 获取当前选择的日期
    const selectedDate = formData.value.visitdate
    
    // 2. 简单验证日期格式
    if (!selectedDate || !/^\d{4}-\d{2}-\d{2}$/.test(selectedDate)) {
        console.warn('日期格式不正确:', selectedDate)
        return
    }
    
    // 3. 可以添加业务逻辑（如限制选择过去日期）
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    
    const visitDate = new Date(selectedDate)
    if (visitDate < today) {
        ElMessage.warning('不能选择过去的日期')
        formData.value.visitdate = '' // 清空选择
        return
    }
    
    console.log('有效看诊日期:', selectedDate)
    
}

    function Dept_select() {
        //formData.deptid 就是当前选中的科室
        service.get("/user/getbydeptid?deptid=" + formData.value.deptid).then(
            res => {
                console.log(res.data)
                doctorData.value = res.data
            }
        )
    }

    function RegistLe_select() {
        // 可以根据需要添加逻辑
        console.log("当前选择的号别ID:", formData.value.registleid);
    }

    function book_select() {
    console.log("病历本选择状态:", formData.value.isbook); // 现在会输出 1 或 0
    // 在这里添加你的逻辑，比如更新费用
    if (formData.value.isbook === 1) {  // 使用数字比较
        formData.value.fee = (formData.value.fee || 0) + 1;  // 如果选择病历本，增加费用
    } else {
        formData.value.fee = (formData.value.fee || 0) - 1;  // 如果取消选择，减少费用
    }
    }
    

    function calculateAge() {
        console.log(formData.value.birthdate)
        const birthdate = new Date(formData.value.birthdate);
        const today = new Date();

        // 计算时间差（毫秒）
        const timeDiff = today - birthdate;
        // 计算天数
        const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
        // 计算月数（近似值）
        const monthsDiff = Math.floor(daysDiff / 30.44);
        // 计算年数
        let yearsDiff = today.getFullYear() - birthdate.getFullYear();
        // 调整年数（如果今年生日还没到）
        const monthCheck = today.getMonth() - birthdate.getMonth();
        if (monthCheck < 0 || (monthCheck === 0 && today.getDate() < birthdate.getDate())) {
            yearsDiff--;
        }
        // 确定显示类型（岁/月/天）
        let ageValue, ageType;

        if (yearsDiff >= 2) {
            ageValue = yearsDiff;
            ageType = '岁';
        } else if (monthsDiff >= 1) {
            ageValue = monthsDiff;
            ageType = '个月';
        } else {
            ageValue = daysDiff;
            ageType = '天';
        }

        // 更新显示
        //console.log("ageType="+ageType)
        //console.log("ageValue="+ageValue)
        formData.value.age = ageValue
        formData.value.agetype = ageType


    }

    onMounted(() => {

        //性别
        service.get("/constantitem/getbytypeid2?id=7").then(
            res => {
                sexData.value = res.data
            }
        )
        //收费方式
        service.get("/constantitem/getbytypeid2?id=5").then(
            res => {
                categories3.value = res.data
            }
        )
        //结算方式
        service.get("/settleCategory/list").then(
            res => {
            categoryData.value = res.data;
        })
        //号别
        service.get("/registLevel/list").then(
            res => {
            registlevelData.value = res.data;
        })
        //挂号科室
        service.get("/dept/list").then(
            res => {
                deptData.value = res.data
                
            }
        )
        //看诊医生
        service.get("/user/getdoctor?usetype=3").then(
            res => {
                doctorData.value = res.data
            }
        )

    })
</script>